package com.project.servlet;

import com.project.ServletObj;
import com.project.bean.UserBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

@ServletObj(url = "/add")
public class AddServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        UserBean user = new UserBean();
        fullBean(req, user);
        resp.getWriter().print(user);
    }

    /**
     * 将请求参数按表单名和属性名一致的原则，封装成实体类对象
     *
     * @param req     请求对象
     * @param beanObj 实体类对象
     */
    private void fullBean(HttpServletRequest req, Object beanObj) {
        Enumeration em = req.getParameterNames();
        try {
            while (em.hasMoreElements()) {
                String key = (String) em.nextElement();
                String value = req.getParameter(key);
                //根据表单名得到属性对象
                Field f = beanObj.getClass().getDeclaredField(key);
                f.setAccessible(true);
                if(f.getType() == String.class){
                    f.set(beanObj,value);
                }else if(f.getType() == int.class || f.getType() ==Integer.class){
                    f.set(beanObj,Integer.parseInt(value));
                }else if(f.getType() == LocalDate.class){
                    f.set(beanObj,LocalDate.parse(value));
                }else if(f.getType() == double.class){
                    f.set(beanObj,Double.parseDouble(value));
                }else if(f.getType() == String[].class){
                    f.set(beanObj,req.getParameterValues(key));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
